# encoding=utf-8

import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

import torndb

from config import *

class DiscussHandler(tornado.web.RequestHandler):
    def post(self):
        if not self.get_secure_cookie('user'):
            self.redirect("/login")
            return
        
        username = self.get_secure_cookie("user")

        try:
            db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
        except:
            return

        user_info = db.get("select * from user where username='"+username+"'")

        title = self.get_argument("title", "")
        content = self.get_argument("content", "")
        anonymous = self.get_argument("anonymous", "")
        pid = self.get_argument("query", "")
        
        if title == "" or content == "" or pid == "":
            self.redirect("/questions?query=" + str(pid))
            return

        if anonymous == "":
            db.execute(u"insert into discuss (title, pid,user,comment) values('" + title +"','" + pid + "','" + username + "','" + content+"')")
        else:
            db.execute(u"insert into discuss (title, pid,comment) values('" + title +"','" + pid + "','" + content+"')")

        self.redirect("/questions?query=" + str(pid))
